package com.swsc.xapp.xroom;

import android.text.TextUtils;
import android.util.Log;

import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.RawQuery;
import androidx.room.Update;
import androidx.sqlite.db.SimpleSQLiteQuery;
import androidx.sqlite.db.SupportSQLiteQuery;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;

public interface BaseDao<T> {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    long save(T t);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void saveAll(T ... t);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void saveCollection(Collection<T> coll);

    @Update
    void update(T t);

    @Delete
    void delete(T t);

    @RawQuery
    List<T> doRawQuery(SupportSQLiteQuery query);

    @RawQuery
    long countRawQuery(SupportSQLiteQuery query);

    @RawQuery
    int deleteRawQuery(SupportSQLiteQuery query);

    default List<T> doRawQuery(String paramSql){
        StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM ").append(getTableName()).append(" WHERE 1 = 1 ");
        if(!TextUtils.isEmpty(paramSql)){
            sqlBuilder.append(paramSql);
        }
        return doRawQuery(new SimpleSQLiteQuery(sqlBuilder.toString()));
    }

    default long countRawQuery(String paramSql){
        StringBuilder sqlBuilder = new StringBuilder("SELECT COUNT(*) FROM ").append(getTableName()).append(" WHERE 1 = 1 ");
        if(!TextUtils.isEmpty(paramSql)){
            sqlBuilder.append(paramSql);
        }
        return countRawQuery(new SimpleSQLiteQuery(sqlBuilder.toString()));
    }

    default String getTableName(){

//        return ((ParameterizedType) getClass().getGenericInterfaces()[0])
//                .getActualTypeArguments()[0].getClass().getName().replace(".", "_");
//        Type[] superInterfaceTypes = getClass().getGenericInterfaces();
        Type superInterfaceType = getClass().getGenericInterfaces()[0];
        Type[] superInterfaceTypes = superInterfaceType.getClass().getGenericInterfaces();
//        String clazzName = superClazzType.getActualTypeArguments()[0].getClass().getName();
        Class<?> clazz = (Class<?>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        String tableName = clazz.getSimpleName();
        Log.d("ez", "getTableName: -->" + tableName);
        return tableName;
    }

    default void deleteAll(){
        StringBuilder sqlBuilder = new StringBuilder("DELETE FROM ").append(getTableName());
        deleteRawQuery(new SimpleSQLiteQuery(sqlBuilder.toString()));
    }
}
